package com.kgcx.dbutils.handler;

import com.kgcx.common.bean.ReturnData;
import com.kgcx.dbutils.service.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 吴刚林
 * @date 2017/11/28
 */
@ControllerAdvice
@ConditionalOnProperty(prefix = "kgcx.dbutils.dict", name = "enable", havingValue = "true")
public class DictTransResponseBodyAdviceAdapter implements ResponseBodyAdvice {
    @Autowired
    private DictService dictService;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request.getMethod().equalsIgnoreCase(HttpMethod.GET.toString());
    }

    @Nullable
    @Override
    public Object beforeBodyWrite(@Nullable Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (null != body && body instanceof ReturnData) {
            ReturnData rd = (ReturnData) body;
            Object data = rd.getData();
            dictService.buildDictValue(data);
        }
        return body;
    }


}
